package cn.stylefeng.guns.modular.gridsystem.controller;

import cn.hutool.core.map.MapUtil;
import cn.stylefeng.guns.core.annotion.BusinessLog;
import cn.stylefeng.guns.core.enums.LogAnnotionOpTypeEnum;
import cn.stylefeng.guns.core.pojo.response.ResponseData;
import cn.stylefeng.guns.core.pojo.response.SuccessResponseData;
import cn.stylefeng.guns.modular.gridsystem.entity.BizDevice;
import cn.stylefeng.guns.modular.gridsystem.entity.BizGateway;
import cn.stylefeng.guns.modular.gridsystem.entity.BizGatewayChannel;
import cn.stylefeng.guns.modular.gridsystem.entity.BizStation;
import cn.stylefeng.guns.modular.gridsystem.model.param.ApplicationRecordParam;
import cn.stylefeng.guns.modular.gridsystem.model.param.BizGatewayParam;
import cn.stylefeng.guns.modular.gridsystem.model.param.DirectoryTreeParam;
import cn.stylefeng.guns.modular.gridsystem.model.param.GatewayImportParam;
import cn.stylefeng.guns.modular.gridsystem.model.result.GatewayResult;
import cn.stylefeng.guns.modular.gridsystem.service.BizDeviceService;
import cn.stylefeng.guns.modular.gridsystem.service.BizGatewayChannelService;
import cn.stylefeng.guns.modular.gridsystem.service.BizGatewayService;
import cn.stylefeng.guns.modular.gridsystem.service.BizStationService;
import cn.stylefeng.guns.modular.gridsystem.utils.CollectorConfigUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * 采集设备 控制器
 *
 * @author: ssy
 * @date: 2021/09/14 11:47
 */
@RestController
@Slf4j
@RequiredArgsConstructor
public class BizGatewayController {

    private final BizGatewayService bizGatewayService;

    private final BizStationService bizStationService;

    private final BizGatewayChannelService bizGatewayChannelService;

    private final BizDeviceService bizDeviceService;

    /**
     * 分页查询采集设备
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @GetMapping("/bizGateway/page")
    @BusinessLog(title = "采集设备_分页查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData page(BizGatewayParam bizGatewayParam) {
        return new SuccessResponseData(bizGatewayService.page(bizGatewayParam));
    }

    /**
     * 分页查询采集设备（配置向导）
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @GetMapping("/bizGateway/guidePage")
    @BusinessLog(title = "采集设备_分页查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData guidePage(BizGatewayParam param) {
        return new SuccessResponseData(bizGatewayService.guidePage(param));
    }

    /**
     * 获取全部采集设备
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @GetMapping("/bizGateway/list")
    @BusinessLog(title = "采集设备_查询所有", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData list(BizGatewayParam bizGatewayParam) {
        return new SuccessResponseData(bizGatewayService.list(bizGatewayParam));
    }

    /**
     * 获取当前登录用户所在部门下的所有网关
     */
    @GetMapping("/bizGateway/listAll")
    @BusinessLog(title = "获取当前登录用户所在部门下的所有网关", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData listAll(BizGatewayParam param) {
        return new SuccessResponseData(bizGatewayService.listAll(param));
    }

    /**
     * 查询所有未申请授权、授权过期、以及审核授权失败的网关
     *
     * @author zxw 2022-12-23 11:24
     */
    @GetMapping("/bizGateway/listNoGrant")
    @BusinessLog(title = "查询所有未申请授权、授权过期、以及审核授权失败的网关", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData listNoGrant(BizGatewayParam param) {
        return new SuccessResponseData(bizGatewayService.listNoGrant(param));
    }

    /**
     * 查看详情采集设备
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @GetMapping("/bizGateway/detail")
    @BusinessLog(title = "采集设备_查看详情", opType = LogAnnotionOpTypeEnum.DETAIL)
    public ResponseData detail(@Validated(BizGatewayParam.detail.class) BizGatewayParam bizGatewayParam) {
        return new SuccessResponseData(bizGatewayService.detail(bizGatewayParam));
    }

    /**
     * 获取网关配置
     *
     * @author zxw 2022/11/11
     */
    @GetMapping("/bizGateway/getConfig")
    @BusinessLog(title = "获取网关配置", opType = LogAnnotionOpTypeEnum.DETAIL)
    public ResponseData getConfig(@Validated(BizGatewayParam.detail.class) BizGatewayParam param) {
        return new SuccessResponseData(bizGatewayService.getConfig(param));
    }

    /**
     * 更新网关配置
     *
     * @author zxw 2022/11/11
     */
    @PostMapping("/bizGateway/updateConfig")
    @BusinessLog(title = "更新网关配置", opType = LogAnnotionOpTypeEnum.UPDATE)
    public ResponseData updateConfig(@RequestBody Map<String, Object> cfg) {
        bizGatewayService.updateConfig(cfg);
        return new SuccessResponseData();
    }

    /**
     * 添加采集设备
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @PostMapping("/bizGateway/add")
    @BusinessLog(title = "采集设备_增加", opType = LogAnnotionOpTypeEnum.ADD)
    public ResponseData add(@RequestBody @Validated(BizGatewayParam.add.class) BizGatewayParam param) {
        bizGatewayService.add(param);
        return new SuccessResponseData();
    }

    @PostMapping("/bizGateway/addGateway")
    @BusinessLog(title = "采集设备_增加", opType = LogAnnotionOpTypeEnum.ADD)
    public ResponseData addGateway(@RequestBody @Validated(BizGatewayParam.add.class) BizGatewayParam param) {
        bizGatewayService.addGateway(param);
        return new SuccessResponseData();
    }

    /**
     * 导入采集设备
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @PostMapping("/bizGateway/importGateway")
    @BusinessLog(title = "采集设备_导入", opType = LogAnnotionOpTypeEnum.IMPORT)
    @Transactional(rollbackFor = Exception.class)
    public ResponseData importGateway(@RequestBody GatewayImportParam param) {
        return new SuccessResponseData(bizGatewayService.importGateway(param));
    }

    /**
     * 删除采集设备
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @PostMapping("/bizGateway/delete")
    @BusinessLog(title = "采集设备_删除", opType = LogAnnotionOpTypeEnum.DELETE)
    @Transactional(rollbackFor = Exception.class)
    public ResponseData delete(@RequestBody @Validated(BizGatewayParam.delete.class) BizGatewayParam bizGatewayParam) {
        bizGatewayService.delete(bizGatewayParam);
        return new SuccessResponseData();
    }

    /**
     * 编辑采集设备
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @PostMapping("/bizGateway/edit")
    @BusinessLog(title = "采集设备_编辑", opType = LogAnnotionOpTypeEnum.EDIT)
    public ResponseData edit(@RequestBody @Validated(BizGatewayParam.edit.class) BizGatewayParam bizGatewayParam) {
        bizGatewayService.edit(bizGatewayParam);
        return new SuccessResponseData();
    }

    /**
     * 编辑采集设备-配置向导
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @PostMapping("/bizGateway/editGateway")
    @BusinessLog(title = "采集设备_编辑", opType = LogAnnotionOpTypeEnum.EDIT)
    public ResponseData editGateway(@RequestBody @Validated(BizGatewayParam.edit.class) BizGatewayParam bizGatewayParam) {
        bizGatewayService.editGateway(bizGatewayParam);
        return new SuccessResponseData();
    }

    /**
     * 修改状态
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @PostMapping("/bizGateway/changeStatus")
    @BusinessLog(title = "采集设备_修改状态", opType = LogAnnotionOpTypeEnum.CHANGE_STATUS)
    public ResponseData changeStatus(@RequestBody @Validated(BizGatewayParam.changeStatus.class) BizGatewayParam bizGatewayParam) {
        bizGatewayService.changeStatus(bizGatewayParam);
        return new SuccessResponseData();
    }

    @PostMapping("/bizGateway/changeSwitch")
    @BusinessLog(title = "采集设备_修改数据上报开关", opType = LogAnnotionOpTypeEnum.CHANGE_STATUS)
    public ResponseData changeSwitch(@RequestBody BizGatewayParam bizGatewayParam) {
        bizGatewayService.changeSwitch(bizGatewayParam);
        return new SuccessResponseData();
    }

    @PostMapping("/bizGateway/batchChangeDataReportStatus")
    @BusinessLog(title = "批量修改网关数据上报开关状态", opType = LogAnnotionOpTypeEnum.CHANGE_STATUS)
    public ResponseData batchChangeDataReportStatus(@RequestBody @Validated(BizGatewayParam.batChangeStatus.class) BizGatewayParam param) {
        bizGatewayService.batchChangeDataReportStatus(param);
        return new SuccessResponseData();
    }

    @GetMapping("/bizGateway/gatewayByGatewayCode")
    public BizGateway gatewayByGatewayCode(BizGatewayParam bizGatewayParam) {
        return bizGatewayService.gatewayByGatewayCode(bizGatewayParam);
    }

    /**
     * 查询网关列表
     *
     * @param stationId
     * @return
     */
    @GetMapping("/bizGateway/getAllListById")
    public Map<String, Object> getAllListByStationId(Integer stationId) {
        // TODO: 2022/12/5 此方法是用于前端站点信息页面调用，待大屏完全剥离系统后需要将此方法直接删除
        BizStation bizStation = bizStationService.getById(stationId);
        Map<String, Object> hashMap = MapUtil.newHashMap();
        hashMap.put("bizStation", bizStation);

        QueryWrapper<BizGateway> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("station_id", stationId);
        List<Map<String, Object>> gatewayList = bizGatewayService.listMaps(queryWrapper);

        gatewayList.forEach(map -> {
            Object gatewayId = map.get("id");
            QueryWrapper<BizGatewayChannel> channelQueryWrapper = new QueryWrapper<>();
            channelQueryWrapper.eq("gateway_id", gatewayId);
            List<Map<String, Object>> channelList = bizGatewayChannelService.listMaps(channelQueryWrapper);
            Set<Integer> devicedIds = new HashSet<>();

            channelList.forEach(map1 -> {
                Integer deviceId = Integer.parseInt(map1.get("device_id").toString());
                BizDevice device = bizDeviceService.getById(deviceId);
                devicedIds.add(deviceId);
                map1.put("device", device);
            });

            map.put("channelList", channelList);
            map.put("deviceNumber", devicedIds.size());
        });
        hashMap.put("gatewayList", gatewayList);
        return hashMap;
    }

    /**
     * 自检
     *
     * @param ip
     * @return
     */
    @GetMapping("/bizGateway/selfTest")
    public ResponseData test(String ip) {
        try {
            String s = CollectorConfigUtil.selfTest(ip);
            JSONObject jsonObject = JSONObject.parseObject(s);
            String code = jsonObject.getString("code");
            if ("200".equals(code)) {
                return ResponseData.success("自检通过");
            } else {
                return ResponseData.error("线路异常");
            }
        } catch (Exception e) {
            return ResponseData.error("线路异常");
        }
    }

    /**
     * 分页查询无站点的采集设备
     *
     * @author ssy
     * @date 2021/09/14 11:47
     */
    @GetMapping("/bizGateway/initGatewayPage")
    @BusinessLog(title = "无站点采集设备_分页查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData initGatewayPage(BizGatewayParam bizGatewayParam) {
        return new SuccessResponseData(bizGatewayService.initGatewayPage(bizGatewayParam));
    }

    @GetMapping("/bizGateway/queryGrantInfo")
    @BusinessLog(title = "查询办公系统上的现有网关授权信息", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData queryGrantInfo() {
        return new SuccessResponseData(bizGatewayService.queryGrantInfo());
    }

    @PostMapping("/bizGateway/batchAddApplicationRecord")
    @BusinessLog(title = "批量添加设备授权申请信息", opType = LogAnnotionOpTypeEnum.UPDATE)
    public ResponseData batchAddApplicationRecord(@RequestBody @Validated(ApplicationRecordParam.grant.class) ApplicationRecordParam param) {
        bizGatewayService.batchAddApplicationRecord(param);
        return new SuccessResponseData();
    }

    @PostMapping("/bizGateway/syncGatewayGrant")
    @BusinessLog(title = "同步网关授权申请审核状态", opType = LogAnnotionOpTypeEnum.UPDATE)
    public ResponseData syncGatewayGrant() {
        bizGatewayService.syncGatewayGrant();
        return new SuccessResponseData();
    }

    /**
     * 获取网关列表树型结构
     *
     * @author zxw 2022-11-18 14:36:55
     */
    @GetMapping("/bizGateway/tree")
    public ResponseData tree(BizGatewayParam param) {
        List<GatewayResult> list = bizGatewayService.list(param);
        DirectoryTreeParam treeParam = new DirectoryTreeParam();
        treeParam.setId("0");
        treeParam.setTitle("全部网关");
        treeParam.setDisabled(true);
        treeParam.setKey("0-0");
        List<DirectoryTreeParam> treeParamList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            DirectoryTreeParam treeParam1 = new DirectoryTreeParam();
            treeParam1.setId(list.get(i).getId().toString());
            treeParam1.setTitle(list.get(i).getGatewayName());
            treeParam1.setDisabled(false);
            treeParam1.setKey(list.get(i).getId().toString());
            treeParamList.add(treeParam1);
        }
        treeParam.setChildren(treeParamList);
        List<DirectoryTreeParam> treeParamList1 = new ArrayList<>();
        treeParamList1.add(treeParam);
        return new SuccessResponseData(treeParamList1);
    }

}
